package org.colin.ds;

import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 多数据源，切面处理类
 * @ClassName: DataSourceAspect
 * @Author: wujiangbo
 * @Date: 2020-01-17 16:37
 * @Version: 1.1.0
 */
@Aspect
@Component
@Slf4j
public class DataSourceAspect implements Ordered {

	@Pointcut("@annotation(org.colin.ds.DataSource)")
	public void dataSourcePointCut() {
	}

	@Around("dataSourcePointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method method = signature.getMethod();
		DataSource ds = method.getAnnotation(DataSource.class);
		if (ds == null) {
			// 没有配置（@DataSource(name = "second")）的话，默认连接第一个数据库
			DynamicDataSource.setDataSource(DataSourceNames.FIRST);
			log.debug("set datasource is " + DataSourceNames.FIRST);
		} else {
			DynamicDataSource.setDataSource(ds.name());
			log.debug("set datasource is " + ds.name());
		}
		try {
			return point.proceed();
		} finally {
			DynamicDataSource.clearDataSource();
			log.debug("clean datasource");
		}
	}

	@Override
	public int getOrder() {
		return 1;
	}
}